import { defineStore } from 'pinia';
import store from '@/store';

import { getDictDetailByCode } from '@/api/system/dictionary';
import type { DicConfigListRow } from '@/api/system/dictionary';
import { getLanguage } from '@/i18n';

/** 获取dic的国际化值的key  */
function getDicLangKey(): string {
	const lang = getLanguage();
	switch (lang) {
		case 'zh':
			return 'dictName';
		case 'en':
			return 'dictEnName';
		default:
			return 'dictName';
	}
}
/** 获取国际化处理后的option */
function dicOptionFormatter(option: DicConfigListRow[]): NormalOption {
	const valueKey = getDicLangKey();
	const arr = option.map(item => {
		return {
			label: item[valueKey],
			value: item.dictData,
		};
	});
	return arr;
}

interface DicState {
	devTypeOption: NormalOption;
	signalTypeOption: NormalOption;
	alarmTypeOption: NormalOption;
	alarmLevelOption: NormalOption;
}

export const useDictionaryStore = defineStore('app-dictionary', {
	state: (): DicState => ({
		devTypeOption: [],
		signalTypeOption: [],
		alarmTypeOption: [],
		alarmLevelOption: [],
	}),
	getters: {},
	actions: {
		/** 设备类型字典 */
		getDevTypeOption() {
			return new Promise(async (resolve, reject) => {
				try {
					const params = { dictTypeCode: 'device_type' };
					const { results } = await getDictDetailByCode(params);
					this.devTypeOption = dicOptionFormatter(results);
					resolve(results);
				} catch (error) {
					reject(error);
				}
			});
		},
		/** 信号点类型字典 */
		getSignalTypeOption() {
			return new Promise(async (resolve, reject) => {
				try {
					const params = { dictTypeCode: 'signal_type' };
					const { results } = await getDictDetailByCode(params);
					this.signalTypeOption = dicOptionFormatter(results);
					resolve(results);
				} catch (error) {
					reject(error);
				}
			});
		},
		/** 信号点类型字典 */
		getAlarmTypeOption() {
			return new Promise(async (resolve, reject) => {
				try {
					const params = { dictTypeCode: 'alarm_type' };
					const { results } = await getDictDetailByCode(params);
					this.alarmTypeOption = dicOptionFormatter(results);
					resolve(results);
				} catch (error) {
					reject(error);
				}
			});
		},
		/** 信号点类型字典 */
		getAlarmLevelOption() {
			return new Promise(async (resolve, reject) => {
				try {
					const params = { dictTypeCode: 'alarm_level' };
					const { results } = await getDictDetailByCode(params);
					this.alarmLevelOption = dicOptionFormatter(results);
					resolve(results);
				} catch (error) {
					reject(error);
				}
			});
		},
	},
});

// Need to be used outside the setup
export function useDictionaryStoreWithOut() {
	return useDictionaryStore(store);
}
